import Flutter
import UIKit
import PangrowthDJX

func JSONConfigPath() -> String! {
    Bundle.main.path(forResource: "SDK_Setting_5318063", ofType:"json")
}

public class PangRowthPlugin: NSObject, FlutterPlugin ,DJXAuthorityConfigDelegate{
    
    private var rootViewController: UIViewController? {
        return UIApplication.shared.windows.first?.rootViewController
    }
    
    public static func register(with registrar: FlutterPluginRegistrar) {
        let channel = FlutterMethodChannel(name: "pang_rowth_plugin", binaryMessenger: registrar.messenger())
        let instance = PangRowthPlugin()
        registrar.addMethodCallDelegate(instance, channel: channel)
    }
    
    public func handle(_ call: FlutterMethodCall, result: @escaping FlutterResult) {
        switch call.method {
        case "getPlatformVersion":
            result("iOS " + UIDevice.current.systemVersion)
            
        case "init":
            handleInit(call, result: result)
            
        case "loadDJX":
            handleLoadDJX(call, result: result)
            
        default:
            result(FlutterMethodNotImplemented)
        }
    }
    
    private func handleInit(_ call: FlutterMethodCall, result: @escaping FlutterResult) {
        do {
            guard let args = call.arguments as? [String: Any] else {
                result(FlutterError(code: "INVALID_ARGUMENTS", message: "参数无效", details: nil))
                return
            }
            
            let djxJson = args["DJXJson"] as? String
            let novJson = args["NOVJson"] as? String
            
            // 初始化DJX SDK
            if let djxJson = djxJson {
                let config = DJXConfig()
                config.logLevel = .debug // 开发环境使用debug，生产环境改为none
                config.authorityDelegate = self
                
                // 检查配置文件路径是否存在
                guard let configPath = JSONConfigPath(), !configPath.isEmpty else {
                    result(FlutterError(code: "CONFIG_PATH_ERROR", message: "SDK配置文件路径无效", details: nil))
                    return
                }
                
                // 初始化SDK
                DJXManager.initialize(withConfigPath: configPath, config: config)
                DJXManager.start { isSuccess, userInfo in
                    if isSuccess {
                        result(true)
                    } else {
                        result(FlutterError(code: "SDK_START_FAILED", message: "SDK启动失败", details: userInfo))
                    }
                }
            } else {
                result(FlutterError(code: "MISSING_DJX_JSON", message: "缺少DJXJson参数", details: nil))
            }
        } catch let error as NSError {
            // 捕获NSError类型的错误
            result(FlutterError(
                code: "INIT_ERROR", 
                message: "初始化过程中发生错误: \(error.localizedDescription)", 
                details: ["domain": error.domain, "code": error.code, "userInfo": error.userInfo]
            ))
        } catch {
            // 捕获其他类型的错误
            result(FlutterError(
                code: "UNKNOWN_ERROR", 
                message: "初始化过程中发生未知错误: \(error.localizedDescription)", 
                details: nil
            ))
        }
    }
    
    private func handleLoadDJX(_ call: FlutterMethodCall, result: @escaping FlutterResult) {
        guard let rootVC = rootViewController else {
            result(FlutterError(code: "NO_ROOT_VC", message: "无法获取根视图控制器", details: nil))
            return
        }
        
        if #available(iOS 12.0, *) {
            let vc = DJXPlayletAggregatePageViewController{config in
                let playletConfig = DJXPlayletConfig()
                playletConfig.freeEpisodesCount = 10
                playletConfig.unlockEpisodesCountUsingAD = 5
                playletConfig.playletUnlockADMode = .common
                config.playletConfig = playletConfig
                config.isShowNavigationItemTitle = false  // 关闭DJX自带的导航栏
                config.isShowNavigationItemBackButton = false  // 关闭DJX自带的返回按钮
            }
            
            // 使用自定义容器，传入标题
            let containerVC = SafeAreaContainerViewController(contentViewController: vc, title: "短剧")
            containerVC.modalPresentationStyle = .fullScreen
            
            rootVC.present(containerVC, animated: true)
            result(true)
        } else {
            result(FlutterError(code: "IOS_VERSION_TOO_LOW", message: "iOS版本过低，需要iOS 12.0及以上", details: nil))
        }
    }
}
